import React, {useRef, useState, useEffect} from "react";
import {
    ActionType, EditableProTable,
    ModalForm, ProColumnType, ProForm,
    ProFormDateTimePicker, ProFormDigit, ProFormRadio,
    ProFormSelect,
    ProFormText,
    ProFormList,
    ProFormGroup,
    ProFormTextArea, ProColumns, ProTable,
} from "@ant-design/pro-components";
import {NetworkListItem} from "@/pages/power/network/data";
import {Button, message} from "antd";
import {dataCenterSelectList} from "@/pages/power/data-center-list/service";
import {organizationSelectList} from "@/pages/organization/org-list/service";
import {NetworkConnTypeEnum} from "@/pages/data.enum";
import {organizationOrderAdd} from "@/pages/power/resource-activate/service";

import {Col, Row, Space} from 'antd';
import {PlusOutlined} from "@ant-design/icons";
import {networkList, networkSelectList} from "@/pages/power/network/service";
import {HostComputerListItem} from "@/pages/power/host-computer/list/data";
import {organizationResourceList} from "@/pages/organization/resource-manager/service";
import {hostComputerDelete} from "@/pages/power/host-computer/list/service";
import {hostComputerConfigNetwork} from "@/pages/power/host-computer/edit/service";



const handleConfigNetwork = async (hostComputerId:string,selectedRows: NetworkListItem[]) => {
    const hide = message.loading('正在配置');
    if (!selectedRows) return true;

    try {
        const result = await hostComputerConfigNetwork({
            hostComputerId: hostComputerId,
            networkIdList: selectedRows.map((row) => row.networkId),
        });
        if (!result.success) {
            throw new Error(result.errorMessage);
        }
        hide();
        message.success('配置成功，即将刷新');
        return true;
    } catch (error) {
        hide();
        message.error('配置失败，请重试');
        return false;
    }
};

type ConfigNetworkProps = {
    modalVisible: boolean;
    currentHostComputerRow: HostComputerListItem;
    onClose: () => void;
    onSuccess: () => void;
};

const columns: ProColumns<NetworkListItem>[] = [
    {
        title: '租户',
        dataIndex: "organizationName",
        valueType: 'text',
        search: false,
        ellipsis: true, // 关闭自动换行
    },
    {
        title: '网络ID',
        dataIndex: 'networkId',
        search: false,
        hidden: true,
        ellipsis: true, // 关闭自动换行
    },
    {
        title: '网络名称(备注)',
        dataIndex: 'networkName',
        search: false,
        ellipsis: true, // 关闭自动换行
    },
    {
        title: '连接类型',
        dataIndex: 'connType',
        search: true,
        valueType: 'select',
        valueEnum: NetworkConnTypeEnum,
        width: 80,
        ellipsis: true, // 关闭自动换行
    },
    {
        title: '互联网IP',
        dataIndex: 'publicIp',
        search: true,
        width: 80,
        ellipsis: true, // 关闭自动换行
        render: (value, record, index) => {
            let result = [];
            for (let i = 0; i < record.publicIpList?.length; i++) {
                if (record.publicIpList[i].bandwidth === 0) {
                    result.push(
                        <div key={i}>
                            <b>{record.publicIpList[i].publicIp}</b>
                            {i < record.publicIpList.length - 1 && <br/>}
                        </div>
                    );
                } else {
                    result.push(
                        <div key={i}>
                            <b>{record.publicIpList[i].publicIp}</b>
                            &nbsp;&nbsp;&nbsp;带宽:&nbsp;{record.publicIpList[i].bandwidth}M
                            {i < record.publicIpList.length - 1 && <br/>}
                        </div>
                    );
                }
            }
            return <div>{result}</div>;
        },
    },
    {
        title: '共享带宽',
        dataIndex: 'topology',
        search: false,
        ellipsis: true, // 关闭自动换行
        render: (value, record, index) => {
            if (record.bandwidth > 0) {
                return <span>{record.bandwidth}M</span>
            } else {
                return '-'
            }
        }
    },
];

const ConfigNetworkModalForm: React.FC<ConfigNetworkProps> = (props) => {
    const {modalVisible, currentHostComputerRow, onClose, onSuccess} = props;
    const [configNetworkModalVisible, handleConfigNetworkModalVisible] = useState<boolean>(modalVisible);
    const [selectedRowsState, setSelectedRows] = useState<NetworkListItem[]>([]);
    /** 分布更新窗口的弹窗 */
    const actionRef = useRef<ActionType>();
    useEffect(() => {
        if (currentHostComputerRow?.networkIdList?.length > 0) {
            const objectArray = currentHostComputerRow?.networkIdList.map(item => ({
                networkId: item, // 将每个字符串作为对象的 name 字段
            }));
            setSelectedRows(objectArray as NetworkListItem[]);
        }
        handleConfigNetworkModalVisible(modalVisible);
    }, [modalVisible]);

    useEffect(() => {
        if (!configNetworkModalVisible) {
            onClose();
        }
    }, [configNetworkModalVisible]);

    return (
        <ModalForm
            title="配置网络"
            width="750px"
            open={configNetworkModalVisible}
            onOpenChange={handleConfigNetworkModalVisible}
            onFinish={async (value) => {
                const success = await handleConfigNetwork(currentHostComputerRow.hostComputerId, selectedRowsState);
                if (success) {
                    onClose()
                    onSuccess()
                    handleConfigNetworkModalVisible(false);
                    if (actionRef.current) {
                        actionRef.current.reload();
                    }
                }
            }}
            modalProps={{destroyOnClose: true}}
            initialValues={{
            }}
        >
            <ProTable<NetworkListItem, API.ListPagination>
                // headerTitle="网络列表"
                actionRef={actionRef}
                rowKey="networkId"
                search={false}
                toolBarRender={() => []}
                scroll={{x: true}}
                request={ (params, sort, filter) =>
                    networkSelectList(params, {}, currentHostComputerRow?.organizationHostComputer?.organizationId) // Pass the fixed parameter to the function
                }
                columns={columns}
                rowSelection={{
                    selectedRowKeys: selectedRowsState?.map((item) => item.networkId!), // 保持选中的行
                    preserveSelectedRowKeys:true,
                    onChange: (_, selectedRows) => {
                        setSelectedRows(selectedRows);
                    },
                }}
                options={false}
                pagination={{
                    pageSize: 5, // 每页显示 10 条数据
                }}
            />
        </ModalForm>
    );
}

export default ConfigNetworkModalForm;
